package com.da.javatest.interview.session2;

import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/4/2 20:16
 * jps -l 相当于 linux下的ps命令
 * jstack 查看进程，例如：jstack 17072
 */
public class Test23DeadLock {
    private final Object LockA = new Object();
    private final Object LockB = new Object();

    private void methodA() throws Exception {
        synchronized (LockA) {
            System.out.println("持有锁A，尝试获取锁B");
            TimeUnit.SECONDS.sleep(2);
            synchronized (LockB) {
                System.out.println("持有锁A，持有锁B");
            }
        }
    }

    private void methodB() throws Exception {
        synchronized (LockB) {
            System.out.println("持有锁B，尝试获取锁A");
            TimeUnit.SECONDS.sleep(2);
            synchronized (LockA) {
                System.out.println("持有锁A，持有锁B");
            }
        }
    }

    public static void main(String[] args) {
        Test23DeadLock t = new Test23DeadLock();
        new Thread(() -> {
            try {
                t.methodA();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                t.methodB();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }
}
